package com.wanpinghui.supplier.user;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.tencent.tauth.Tencent;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.utils.QRCodeUtil;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserInformation;
import com.wanpinghui.wphlibrary.share.ThirdShareManager;
import com.wanpinghui.wphlibrary.share.entity.ShareBean;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.permission.MPermission;
import com.yunshl.yunshllibrary.permission.annotation.OnMPermissionDenied;
import com.yunshl.yunshllibrary.permission.annotation.OnMPermissionNeverAskAgain;
import com.yunshl.yunshllibrary.permission.util.MPermissionUtil;
import com.yunshl.yunshllibrary.utils.BitmapUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.view.YunShlPopupWinow;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import retrofit.callback.YRequestCallback;
import rx.functions.Action1;

/**
 * Created by tg596 on 2018/1/11.
 */

@ContentView(R.layout.layout_activity_qrcodecard)
public class QRcodeCardActivity extends BaseActivity {

    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser tpl_title;

    @ViewInject(R.id.root_view)
    private LinearLayout root_view;

    @ViewInject(R.id.ll_qrcode)
    private LinearLayout ll_qrcode;

    @ViewInject(R.id.iv_qrcode)
    private ImageView iv_qrcode;

    @ViewInject(R.id.rl_info)
    private RelativeLayout rl_info;

    @ViewInject(R.id.iv_head)
    private ImageView iv_head;

    @ViewInject(R.id.tv_name)
    private TextView tv_name;

    @ViewInject(R.id.tv_com)
    private TextView tv_com;

    @ViewInject(R.id.btn_share)
    private ThrottleButton btn_share;

    @ViewInject(R.id.btn_save)
    private ThrottleButton btn_save;

    private UserBean userBeanInfo;
    private UserInformation userBean;
    private int userId;

    private Bitmap logoBitmap;

    public static final int WRITE_REQUEST_CODE = 100;

    // 权限控制  读取权限
    public static final String[] WRITE_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};
    private YunShlPopupWinow popupWinow;


    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        userBeanInfo = UserInfoUtil.getUserInfo();
        if (userBeanInfo != null && userBeanInfo.getUser() != null) {
            userBean = userBeanInfo.getUser();
            userId = Integer.parseInt(userBean.getId());
            tv_name.setText(userBean.getNickname());
            if (TextUtil.isNotEmpty(userBean.getCom())) {
                if (TextUtil.isNotEmpty(userBean.getPos())) {
                    tv_com.setText(userBean.getCom() + " | " + userBean.getPos());
                } else {
                    tv_com.setText(userBean.getCom() + " | 暂无");
                }
            } else {
                tv_com.setText("个体工程商");
            }
            if (TextUtil.isNotEmpty(userBean.getAvatar())) {
                Glide.with(getApplicationContext())
                        .load(userBean.getAvatar())
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.RESULT)

                        .bitmapTransform(new CropCircleTransformation(getApplicationContext()))
                        .placeholder(R.mipmap.my_bg_head_default)
                        .into(new SimpleTarget<GlideDrawable>() {
                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                                iv_head.setImageDrawable(resource);
                                Glide.with(getApplicationContext())
                                        .load(userBean.getAvatar())
                                        .asBitmap().into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                        iv_head.setImageBitmap(resource);
                                        logoBitmap = resource;
                                        Bitmap bitmap = QRCodeUtil.createQRCodeBitmap("这是万屏汇的二维码:" + userId, 1000, logoBitmap, ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryBlue));

                                        iv_qrcode.setImageBitmap(bitmap);
                                    }
                                });
                            }
                        });
            } else {
                logoBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.my_icon_head_default);
                Bitmap bitmap = QRCodeUtil.createQRCodeBitmap("这是万屏汇的二维码:" + userId, 1000, logoBitmap, ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryBlue));
                iv_qrcode.setImageBitmap(bitmap);
            }
        }

    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void bindEvents() {
        tpl_title.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_share.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(QRcodeCardActivity.this).inflate(R.layout.view_dialog_share, null);
                if (popupWinow == null)
                    popupWinow = new YunShlPopupWinow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                view.findViewById(R.id.ll_qq).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                     //   ShareBean shareBean = new ShareBean();
                        ThirdShareManager.getInstance().shareToQQ(QRcodeCardActivity.this,getShareBean1(), new YRequestCallback<Object>() {
                            @Override
                            public void onSuccess(Object var1) {
                         //       showWarningText("分享成功");

                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {

                            }
                        });
                        popupWinow.dismiss();
                    }
                });
                view.findViewById(R.id.ll_WXPY).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                     //   ShareBean shareBean = new ShareBean();
                        ThirdShareManager.getInstance().shareToWeChat(getShareBean(), true, new YRequestCallback() {
                            @Override
                            public void onSuccess(Object var1) {
                          //      showWarningText("分享成功");
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {

                            }
                        });
                        popupWinow.dismiss();
                    }
                });
                view.findViewById(R.id.ll_WXPYQ).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       // ShareBean shareBean = new ShareBean();
                        ThirdShareManager.getInstance().shareToWeChat(getShareBean(), false, new YRequestCallback() {
                            @Override
                            public void onSuccess(Object var1) {
                       //         showWarningText("分享成功");
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {

                            }
                        });
                        popupWinow.dismiss();
                    }
                });
                popupWinow.setCommonConfig(QRcodeCardActivity.this, YunShlPopupWinow.AnimaDirect.DIRECT_BOTTOM_TOP);
                popupWinow.showAtLocation(findViewById(R.id.root_view), Gravity.BOTTOM, 0, 0);
            }
        });

        btn_save.setOnThrottleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                generateBitmap(ll_qrcode, QRcodeCardActivity.this);
            }
        });


    }

    private ShareBean getShareBean() {
        ShareBean shareBean = new ShareBean();
        shareBean.type = ShareBean.Type.TYPE_IMAGE;
        shareBean.img_ = me.nereo.multi_image_selector.utils.BitmapUtil.saveBitmapToFile(this,loadBitmapFromViewBySystem(ll_qrcode),"QRcode",80,true);
//        shareBean.img_ = BitmapUtil.insertImage1(getContentResolver(), loadBitmapFromViewBySystem(ll_qrcode), "", "", this);
        return shareBean;
    }

    private ShareBean getShareBean1() {
        ShareBean shareBean = new ShareBean();
        shareBean.type = ShareBean.Type.TYPE_IMAGE;
        final String filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()+"/image"+ "QRcode" + ".png";
        shareBean.img_ = saveBitmapToLocal(loadBitmapFromViewBySystem(ll_qrcode),filepath);
        //   shareBean.img_ = BitmapUtil.insertImage1(getContentResolver(), loadBitmapFromViewBySystem(ll_qrcode), "", "", this);
        return shareBean;
    }

    /**
     * 保存图像到本地
     */
    public String saveBitmapToLocal(Bitmap bm,String filepath) {
        String path;
        // final String filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/IMG_" + System.currentTimeMillis() + ".png";
        try {
            File file = new File(filepath);

            FileOutputStream fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            path = file.getAbsolutePath();

        } catch (FileNotFoundException e) {

            e.printStackTrace();
            return null;
        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }finally {
            if (bm != null && !bm.isRecycled()) {
                bm.recycle();  //回收图片所占的内存
                System.gc();  //提醒系统及时回收
            }
        }

        return path;
    }



    private static Bitmap loadBitmapFromViewBySystem(LinearLayout v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(),
                v.getHeight()
                , Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }

    @Override
    public void initData() {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, null);
    }

    public void generateBitmap(LinearLayout mContentRootView, Activity activity) {
        if (MPermission.havePermission(activity, MPermission.Type.PERMISSION_STORAGE)) {
            LoadingDialog.Build(activity).setContent("正在保存").show();
            Bitmap bitmap = Bitmap.createBitmap(mContentRootView.getWidth(),
                    mContentRootView.getHeight()
                    , Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            mContentRootView.draw(canvas);
            //     final String filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()+"/Camera" + "/IMG_" + System.currentTimeMillis() + ".png";
            //  final String filepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/IMG_" + System.currentTimeMillis() + ".png";
            saveBitmapToLocal(bitmap, activity);
        } else {
            MPermission.with(activity).addRequestCode(WRITE_REQUEST_CODE).permissions(WRITE_PERMISSIONS).request();
        }
    }

    /**
     * 保存图像到本地
     */
    public String saveBitmapToLocal(Bitmap bm, Activity activity) {
        //      Context context = null;
        String path = BitmapUtil.insertImage(activity.getContentResolver(), bm, "", "");
//        Observable.timer(1500, TimeUnit.MILLISECONDS, Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() {
//            @Override
//            public void call(Long aLong) {
        LoadingDialog.dismissDialog();
        showWarningText("保存成功");
//            }
//        }, new Action1<Throwable>() {
//            @Override
//            public void call(Throwable throwable) {
//
//            }
//        });
        return path;
    }


    @OnMPermissionDenied(WRITE_REQUEST_CODE)
    public void onsavePermissionDenied() {
        List<String> deniedPermissions = MPermission.getDeniedPermissions(this, WRITE_PERMISSIONS);
        String tip = "您拒绝了权限" + MPermissionUtil.toString(deniedPermissions) + "，无法开启保存";
        showWarningText(tip);
    }

    @OnMPermissionNeverAskAgain(WRITE_REQUEST_CODE)
    public void onsavePermissionDeniedAsNeverAskAgain() {
        List<String> deniedPermissions = MPermission.getDeniedPermissionsWithoutNeverAskAgain(this, WRITE_PERMISSIONS);
        List<String> neverAskAgainPermission = MPermission.getNeverAskAgainPermissions(this, WRITE_PERMISSIONS);
        StringBuilder sb = new StringBuilder();
        sb.append("无法开启保存，请到系统设置页面开启权限");
        sb.append(MPermissionUtil.toString(neverAskAgainPermission));
        if (deniedPermissions != null && !deniedPermissions.isEmpty()) {
            sb.append(",下次询问请授予权限");
            sb.append(MPermissionUtil.toString(deniedPermissions));
        }
        showWarningText(sb.toString());
    }
}
